﻿using System.ComponentModel;
using Inovout.Business;
using System;
using System.Linq.Expressions;
using System.Reflection;
using Castle.Core.Logging;

namespace Inovout.Gui.Wpf.ViewModels
{
    public abstract class BaseViewModel : INotifyPropertyChanged
    {
        internal ILogger logger;
        protected ILogger Logger
        {
            get { return logger; }
        }


        private bool isChanged;
        public bool IsChanged
        {
            get { return isChanged; }
        }

        private IViewDataDictionary viewData;

        public virtual IViewDataDictionary ViewData
        {
            get {
                return viewData; 
            }
            internal set 
            {
                viewData = value;
            }
        }
        //protected void SetProperty<T>(Expression<Func<T>> propertyAccess, object value)
        //{
        //    PropertyInfo propertyInfo = GetPropertyInfo(propertyAccess);
        //    propertyInfo.GetGetMethod().Invoke();
        //}


        #region Propertychanged

        protected void OnPropertyChanged<T>(Expression<Func<T>> propertyAccess)
        {
            var propertyName = GetPropertyName(propertyAccess);
            OnPropertyChanged(propertyName);
        }

        protected static PropertyInfo GetPropertyInfo<T>(Expression<Func<T>> propertyAccess)
        {
            var expression = (MemberExpression)propertyAccess.Body;
            return expression.Member as PropertyInfo;
        }

        protected static string GetPropertyName<T>(Expression<Func<T>> propertyAccess)
        {
            var propertyName = GetPropertyInfo(propertyAccess).Name;
            return propertyName;
        }

        private void OnPropertyChanged(string propertyName)
        {
            isChanged = true;
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                var e = new PropertyChangedEventArgs(propertyName);
                handler(this, e);
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }

}
